// 本地存储类
class Storages {
	constructor() {}
	getitem(key) {
		const obj = window.localStorage.getItem(key)
		try {
			return JSON.parse(obj)
		} catch {
			return obj
		}
	}
	setItem(key, val) {
		if (typeof val === 'object') {
			window.localStorage.setItem(key, JSON.stringify(val))
		} else {
			window.localStorage.setItem(key, val)
		}
	}
	removeItem(key) {
		window.localStorage.removeItem(key)
	}
}
// 默认头像
const defalutAvatar =
	'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic_source%2F30%2F90%2F40%2F309040a0602c672cebc6ab3a1bbbc8cd.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1651317121&t=53355bbe748ae845f41cd5e9c06bc330'
// 用户类
class User {
	constructor(obj) {
		// es6 对象结构语法
		console.log(obj)
		const { account, password, avatar } = obj || {}
		this.avatar = avatar || defalutAvatar
		this.account = account || 'llvry'
		this.password = password || '123456'
	}
	// 登录
	login(userImpl) {
		// es6 对象结构语法
		const { account, password } = userImpl
		// 登录验证前 先获取存储的 用户账号和密码
		const mysqlUser = st.getitem('mysqlUser') || []
		let flag = false
		for (let index = 0; index < mysqlUser.length; index++) {
			const item = mysqlUser[index]
			if (item.account === account && item.password === password) {
				flag = true
				break
			}
		}
		if (flag) {
			// 保存当前登录信息                    // 对象合并 类似 Object.assign
			st.setItem('user', { ...userImpl, ...{ avatar: defalutAvatar } })
			// 登录成功
			window.location.href = './chart.html'
		} else {
			alert('账号或密码错误')
		}
	}
	// 退出登录
	loginOut() {
		// 删除当前用户
		Storage.removeItem('user')
	}
}
//初始化创建对象
const st = new Storages()

function isExist(account, password) {
	console.log(st.getitem('mysqlUser'))
	const mysqlUserAccount = st.getitem('mysqlUser') || []
	let flag = false
	for (let index = 0; index < mysqlUserAccount.length; index++) {
		const element = mysqlUserAccount[index]
		if (element.account == account) {
			flag = true
			break
		}
	}
	// 如果最后结果为true 说明账号已经注册过了
	return flag
}
function addStore(userObj) {
	const mysqlUser = st.getitem('mysqlUser') || []
	mysqlUser.push(userObj)
	st.setItem('mysqlUser', mysqlUser)
}
function getCurrentUser() {
	return st.getitem('user')
}
function removeCurrentUser(key) {
	return st.removeItem(key)
}
